<?php

namespace App\Facades;

use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dcdn\Dcdn;

class AliyunDcdn extends AliyunFacade
{
    protected array $config = [
        [
            'functionName' => 'gzip',
            'functionArgs' => [
                'argName' => 'enable',
                'argValue' => 'on',
            ],
        ],
        [
            'functionName' => 'brotli',
            'functionArgs' => [
                'argName' => 'enable',
                'argValue' => 'on',
            ],
        ],
        [
            'functionName' => 'tesla',
            'functionArgs' => [
                [
                    'argName' => 'enable',
                    'argValue' => 'on',
                ],
                [
                    'argName' => 'trim_js',
                    'argValue' => 'on',
                ],
                [
                    'argName' => 'trim_css',
                    'argValue' => 'on',
                ],
            ],
        ],
    ];

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function total(): int
    {
        $res = Dcdn::v20180115()
            ->describeDcdnUserDomains()
            ->withPageSize(1)
            ->withPageNumber(1)
            ->request();

        return $res->get('TotalCount');
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function perform(string $domains): void
    {
        $domains = str_replace('*', '', $domains);

        Dcdn::v20180115()
            ->batchSetDcdnDomainConfigs()
            ->withDomainNames($domains)
            ->withFunctions(json_encode($this->config))
            ->request();
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function store(string $host, string $ossBucket): void
    {
        $sources = [
            [
                'content' => $ossBucket,
                'type' => 'oss',
                'priority' => '20',
                'port' => 80,
                'weight' => 100,
            ],
        ];

        Dcdn::v20180115()
            ->AddDcdnDomain()
            ->withDomainName(str_replace('*', '', $host))
            ->withSources(json_encode($sources))
            ->request();
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function setCertificate(string $host, string $public, string $private): void
    {
        Dcdn::v20180115()
            ->setDcdnDomainCertificate()
            ->withDomainName(str_replace('*', '', $host))
            ->withCertType('upload')
            ->withSSLProtocol('on')
            ->withSSLPub($public)
            ->withSSLPri($private)
            ->request();
    }
}
